package com.fengdi.everyday.middle;

import java.util.HashMap;
import java.util.Map;

public class LongestPalindrome {
    public int longestPalindrome(String[] words) {
        HashMap<String, Integer>  map = new HashMap<>();

        for(String s : words) {
            map.put(s, map.getOrDefault(s, 0) + 1);
        }

        int res = 0;
        boolean mid = false;
        for(Map.Entry<String, Integer> entry : map.entrySet()) {
            String word = entry.getKey();
            Integer value = entry.getValue();
            String rev = "" + word.charAt(1) + word.charAt(0);

            if(word.equals(rev)) {
                if(value % 2 == 1) {
                    mid = true;
                }
                res += 2 * (value / 2 * 2);
            }else if(word.compareTo(rev) > 0) {
                res += 4 * Math.min(map.getOrDefault(word, 0), map.getOrDefault(rev, 0));
            }
        }

        if(mid) res += 2;
        return res;
    }

}
